#include "textsearchdialog.h"

TextSearchDialog::TextSearchDialog(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::TextSearchDialog) {
    ui->setupUi(this);
    initialize();
}

TextSearchDialog::~TextSearchDialog() {
    delete ui;
}

void TextSearchDialog::initialize() {
    // 设置窗口属性，包括最大化按钮
    Qt::WindowFlags flags = this->windowFlags();
    flags |= Qt::WindowMaximizeButtonHint; // 显示最大化按钮
    this->setWindowFlags(flags);

    //this->setMinimumHeight(595);
    //this->setMinimumWidth(740);
    this->setModal(true);//设置为阻塞
    plainTextEdit = ui->plainTextEdit;
    settingManage = SettingManage::getInstance();
    listWidget = ui->listWidget;
    lineEdit = ui->lineEdit;
    rootPath = settingManage->getRootPath();
    codec = QTextCodec::codecForName("UTF-8");
    //
    QFont font = settingManage->getTextFont();
    plainTextEdit->setFont(font);
    //
    QFont f = listWidget->font();
    f.setPointSize(f.pointSize() + 2);
    listWidget->setFont(f);
    //
    plainTextEdit->hide();

    // 设置列表控件尺寸策略
    listWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 禁用水平滚动条

    // 设置分割器策略
    ui->splitter->setStretchFactor(0, 1); // 列表部分
    ui->splitter->setStretchFactor(1, 2); // 文本编辑部分

    // 确保窗口布局可以自动调整
    this->layout()->setContentsMargins(2, 2, 2, 2);
}

void TextSearchDialog::showEvent(QShowEvent *event) {
    // 调用基类的showEvent函数
    QDialog::showEvent(event);

    // 关键代码：强制取消最大化并设置默认大小
    if (isMaximized()) {
        showNormal(); // 取消最大化状态
    }
    resize(800, 600); // 设置默认尺寸

    // 可选：窗口居中（相对父窗口或屏幕）
    QPoint centerPos;
    if (parentWidget()) {
        centerPos = parentWidget()->geometry().center() - rect().center();
    } else {
        centerPos = QApplication::primaryScreen()->geometry().center() - rect().center();
    }
    move(centerPos);

    // 将焦点设置到QLineEdit上（示例中的lineEdit变量名替换为你的QLineEdit变量名）
    if (lineEdit) {
        lineEdit->setFocus();
    }
}

void TextSearchDialog::on_lineEdit_textChanged(const QString &arg1) {
    qDebug() << arg1;
}


void TextSearchDialog::searchInDirectory(const QDir &dir, const QString &keyword) {
    QStringList fileList = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
    int maxw=1500;

    for (const QString &file : fileList) {
        QString filePath = dir.filePath(file);
        QStringList fileContent = FileUtils::readFileByLine(filePath);

        for (int i = 0; i < fileContent.size(); ++i) {
            QString line = fileContent[i];
            int lineNumber = i + 1;
            if (line.contains(keyword, Qt::CaseInsensitive)) {
                QString txt = "(" + line.trimmed() + ")";
                QString relativePath = dir.dirName() + "/" + file;

                SearchItemWidget *customWidget = new SearchItemWidget();
                customWidget->setLeftText(txt);
                customWidget->setRightText(relativePath + " " + QString::number(lineNumber));
                customWidget->filePath = relativePath;
                customWidget->lineNumber = lineNumber;
                customWidget->leftLabel->setMaximumWidth(maxw);

                //QString result = txt + "\t" + relativePath + " " + QString::number(lineNumber);

                QListWidgetItem *item = new QListWidgetItem();
                item->setSizeHint(customWidget->sizeHint());
                listWidget->addItem(item);
                listWidget->setItemWidget(item, customWidget);
            }
        }
    }

    QStringList dirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const QString &subdir : dirList) {
        QDir nextDir(dir.filePath(subdir));
        searchInDirectory(nextDir, keyword);
    }
}

void TextSearchDialog::on_listWidget_itemSelectionChanged() {
    plainTextEdit->show();
    QListWidgetItem *selectedItem = listWidget->currentItem(); // 获取当前选中的条目
    if (!selectedItem) return;
    int currentRow = listWidget->currentRow();
    SearchItemWidget *customWidget = qobject_cast<SearchItemWidget *>(listWidget->itemWidget(selectedItem));
    QString filePath = customWidget->filePath;
    int lineNumber = customWidget->lineNumber;
    QString absName = QDir(rootPath).filePath(filePath);
    QString text = FileUtils::getFileString(absName);

    plainTextEdit->setPlainText(text);
    plainTextEdit->goToLine(lineNumber);

    QString rightLabelext = customWidget->rightLabel->text();
    this->setWindowTitle(m_title+" - "+rightLabelext);

    qDebug() << currentRow << filePath << lineNumber;
}

void TextSearchDialog::on_lineEdit_returnPressed() {
    QString arg1 = lineEdit->text();
    qDebug() << "on_lineEdit_returnPressed" << arg1;

    this->setWindowTitle(m_title);

    listWidget->clear();
    plainTextEdit->clear();
    if (arg1.isEmpty()) {
        plainTextEdit->hide();
        return;
    }

    QDir rootDir(rootPath);
    searchInDirectory(rootDir, arg1);
    //
    // 获取条目数量
    int itemCount = listWidget->count();

    // 检查是否有条目
    if (itemCount > 0) {
        // 选中第一个条目
        listWidget->setCurrentRow(0);
    }
}
